package gov.child.service.impl;

import gov.child.dao.UserDao;
import gov.child.entities.po.EUser;
import gov.child.entities.vo.Auth;
import gov.child.entities.vo.User;
import gov.child.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author fzh
 * @since 2017/9/13
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public boolean save(String username, String password, String phone) {
        EUser user = new EUser();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        userDao.save(user);
        return true;
    }

    @Override
    public User find(Auth auth) {
        int o = auth.getOption();
        User user;
        switch (o) {
            case Auth.BY_USERNAME:
                user = doLoginByUsername(auth.getKey(), auth.getPassword());
                break;
            case Auth.BY_PHONE:
                user = doLoginByPhone(auth.getKey(), auth.getPassword());
                break;
            case Auth.BY_ID_NUM:
                user = doLoginByIDNum(auth.getKey(), auth.getPassword());
                break;
            default:
                user = User.EMPTY_USER_INFO;
        }
        return user;
    }

    @Override
    public boolean update(User user) {
        EUser u = User.parseTo(user);
        userDao.update(u);
        return true;
    }

    //////////////////////////////////////////
    //
    //    Real Method of doLogin
    //
    //////////////////////////////////////////

    private User doLoginByUsername(String username, String password) {
        EUser user = userDao.findByUsernameAndPassword(username, password);
        if (Objects.isNull(user)) return User.EMPTY_USER_INFO;
        else return User.parseFrom(user);
    }

    private User doLoginByPhone(String phone, String password) {
        EUser user = userDao.findByPhoneAndPassword(phone, password);
        if (Objects.isNull(user)) return User.EMPTY_USER_INFO;
        else return User.parseFrom(user);
    }

    private User doLoginByIDNum(String idNum, String password) {
        EUser user = userDao.findByIDNumAndPassword(idNum, password);
        if (Objects.isNull(user)) return User.EMPTY_USER_INFO;
        else return User.parseFrom(user);
    }
}
